﻿hpxAdminApp.controller('addressController', function ($scope, $rootScope, $state, API_URL, NgTableParams, addressService) {
    var emptyEntity = {};
    var newEntity = angular.copy(emptyEntity, newEntity);
    

    $scope.filter = {
        ProvinceID: 1
        
    };

    //获取所有省级地址
    addressService.queryAll().then(function (data) {
        $scope.AddressData = data;
        $scope.filterProvinceChange();
    });
    //获取对应省的所有市级地址
    $scope.filterProvinceChange = function () {
        return addressService.queryCity($scope.filter.ProvinceID).then(function (data) {
            $scope.CityData = data;
            $scope.filter.CityID = data[0].id;
            $scope.filter.parent_address_id = data[0].id;

            $scope.reflash();
        });
    }


    //获取对应市的所有区县级地址
    $scope.filterCityChange = function () {
        return addressService.queryDstrict($scope.filter.CityID).then(function (data) {
            $scope.DstrictData = data;
        });
    };

    //根据关键字，上级地址id获取数据
    $scope.tableParams = new NgTableParams({sorting: {'address_code': 'asc'}}, {
        getData: function (params) {
            /*return addressService.query(params, $scope.filter.parent_address_id, $scope.filter.keyword).then(function (data) {
                $scope.first = $scope.getFirst(params);
                return data;
            }); */
            return addressService.queryDstrict($scope.filter.CityID).then(function (data) {
                $scope.first = $scope.getFirst(params);
                $scope.DstrictData = data;
                return data;
            });
        }

    });

    // 刷新
    $scope.reflash = function () {
        $scope.tableParams.reload();
    };

    $scope.edit = function (data) {
        if (data == null) {
            $scope.model = newEntity;       //弹出新建窗口
            $('#modal-add').modal('show');
        }
        else {
            $scope.model = angular.copy(data);      //弹出修改窗口
            $('#modal-edit').modal('show');
        }
    };

    $scope.save = function () {
        if ($scope.model.id == null) {
            //新建地址信息
            addressService.add($scope.model).then(function (data) {
                $scope.tableParams.reload();
                angular.copy(emptyEntity, newEntity);
                $scope.editForm.$setPristine();
                $('#modal-edit').modal('hide');
            });
        }
        else {
            //修改地址信息
            addressService.update($scope.model).then(function (data) {
                $scope.tableParams.reload();
                $scope.editForm.$setPristine();
                $('#modal-edit').modal('hide');
            });
        }
    };
    //删除某条地址信息；刷新列表
    $scope.remove = function (data) {
        if (confirm('确定要删除 ' + data.address_name + ' 吗？')) {
            addressService.remove(data.id).then(function (data) {
                $scope.tableParams.reload();
            });
        }
    };
});
